import os.path
from datetime import datetime, date
from typing import Any

from django.db.models import Q
from django.forms import model_to_dict
from django.shortcuts import render

# Create your views here.
from django.http.response import HttpResponse
import json
# 取消当前函数防跨域站请求伪造功能
from django.views.decorators.csrf import csrf_exempt

from rest_framework.decorators import api_view  # rest_framework 虚拟环境有，真实环境没有识别不到？？
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http.response import JsonResponse

from soft.models import TbSoft


@csrf_exempt
def example_function():
    pass


def login(request):
    if request.method == 'GET':
        result = {}
        user_name = request.GET.get('userName')
        mobile = request.GET.get('mobile')
        data = request.GET.get('data')
        result['userName'] = user_name
        result['mobile'] = mobile
        result["data"] = data
        result = json.dumps(result)
        return HttpResponse(result)


def login_post(request):
    if request.method == 'POST':
        result = {}
        user_name = request.POST.get('userName')
        password = request.POST.get('password')
        result['userName'] = user_name
        result['password'] = password
        result = json.dumps(result)
        return HttpResponse(result)
    else:
        # 需要在settings.py里设置才有识别到: login.html
        return render(request=request, template_name='login.html')


# 写 api 接口
@api_view(['GET'])
def example_view(request):
    if request.method == 'GET':
        result = {}
        user_name = request.GET.get('userName')
        mobile = request.GET.get('mobile')
        data = request.GET.get('data')
        result['userName'] = user_name
        result['mobile'] = mobile
        result["data"] = data
        result = json.dumps(result)
        return HttpResponse(result)


@api_view(['GET'])
def my_api_view(request):
    content = {'message': 'Hello, World!'}
    return Response(content)


# 使用APIView类的方式
class MyAPIView(APIView):
    @staticmethod
    def get_content(request):
        content = {'message': 'Hello, World!'}
        return Response(content)


@api_view(['GET'])
def test_json_response(request):
    return JsonResponse(data={'result': "ok"})


@api_view(['GET', 'POST', 'DELETE'])
def soft_detail(request, pk):
    try:
        soft = TbSoft.objects.get(pk=pk)  # objects 阴影
    except TbSoft.DoesNotExist:  # DoesNotExist 阴影
        # status.HTTP_404_NOT_FOUND 表示资源未找到
        return JsonResponse(status=404, data={'message': 'Not found'})
    return HttpResponse(json.dumps({
        "code": 200,
        "message": "GET / PUT / DELETE soft",
        "data": soft.to_dict()
    }))


class ComplexEncoder(json.JSONEncoder):
    def default(self, o: Any) -> Any:
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, date):
            return o.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, o)

@api_view
def query_soft_fuzzy(request):
    if request.method == 'POST':
        params = {}
        search = [Q(soft_name__icontains=k) | Q(soft_name__contains=k) for k in request.data.get('softName', [])]
        # 查出只能有一条，多了报错
        soft = TbSoft.objects.get(*search)
        return HttpResponse(json.dumps({
            "code": 200,
            "message": "success",
            "params": params,
            "data": soft.git_url,
            "pageSize": 1,
            "current": 20,
            "total": ""
        }))
    elif request.method == 'GET':
        print(os.path.dirname(__file__), "\n")
        result = []
        for soft in TbSoft.objects.filter.all().order_by("-modify_time"):
            # soft.to_dict()
            result.append(model_to_dict(soft))
        return HttpResponse(json.dumps(result, cls=ComplexEncoder))

